var util = require('util');
var UUID = require('node-uuid');

function RTC() {
  this.sockets = [];
  this.rooms = {};
  /*	this.on('__join', function(data, socket) {
  		console.log(this.sockets.length);
  		var ids = [],
  			i, m,
  			room = data.room || "__default",
  			curSocket,
  			curRoom;

  		curRoom = this.rooms[room] = this.rooms[room] || [];

  		for (i = 0, m = curRoom.length; i < m; i++) {
  			curSocket = curRoom[i];
  			if (curSocket.id === socket.id) {
  				continue;
  			}
  			ids.push(curSocket.id);
  			curSocket.send(JSON.stringify({
  				"eventName": "_new_peer",
  				"data": {
  					"socketId": socket.id
  				}
  			}), errorCb);
  		}

  		curRoom.push(socket);
  		socket.room = room;

  		socket.send(JSON.stringify({
  			"eventName": "_peers",
  			"data": {
  				"connections": ids,
  				"you": socket.id
  			}
  		}), errorCb);

  		this.emit('new_peer', socket, room);
  	});

  	this.on('__ice_candidate', function(data, socket) {
  		var soc = this.getSocket(data.socketId);

  		if (soc) {
  			soc.send(JSON.stringify({
  				"eventName": "_ice_candidate",
  				"data": {
  					"label": data.label,
  					"candidate": data.candidate,
  					"socketId": socket.id
  				}
  			}), errorCb);

  			this.emit('ice_candidate', socket, data);
  		}
  	});

  	this.on('__offer', function(data, socket) {
  		var soc = this.getSocket(data.socketId);

  		if (soc) {
  			soc.send(JSON.stringify({
  				"eventName": "_offer",
  				"data": {
  					"sdp": data.sdp,
  					"socketId": socket.id
  				}
  			}), errorCb);
  		}
  		this.emit('offer', socket, data);
  	});

  	this.on('__answer', function(data, socket) {
  		var soc = this.getSocket(data.socketId);
  		if (soc) {
  			soc.send(JSON.stringify({
  				"eventName": "_answer",
  				"data": {
  					"sdp": data.sdp,
  					"socketId": socket.id
  				}
  			}), errorCb);
  			this.emit('answer', socket, data);
  		}
  	});
  */
}

var errorCb = function(error) {
  console.log(error);
};

RTC.prototype.addSocket = function(socket) {
  this.sockets.push(socket);
};

RTC.prototype.removeSocket = function(socket) {
  var i = this.sockets.indexOf(socket),
    room = socket.room;
  this.sockets.splice(i, 1);
  if (room) {
    i = this.rooms[room].indexOf(socket);
    this.rooms[room].splice(i, 1);
    if (this.rooms[room].length === 0) {
      delete this.rooms[room];
    }
  }
};

RTC.prototype.broadcast = function(data, errorCb) {
  var i;
  for (i = this.sockets.length; i--;) {
    this.sockets[i].send(data, errorCb);
  }
};

RTC.prototype.broadcastInRoom = function(room, data, errorCb) {
  var curRoom = this.rooms[room],
    i;
  if (curRoom) {
    for (i = curRoom.length; i--;) {
      curRoom[i].send(data, errorCb);
    }
  }
};

RTC.prototype.getRooms = function() {
  var rooms = [],
    room;
  for (room in this.rooms) {
    rooms.push(room);
  }
  return rooms;
};

RTC.prototype.getSocket = function(id) {
  var i,
    curSocket;
  if (!this.sockets) {
    return;
  }
  for (i = this.sockets.length; i--;) {
    curSocket = this.sockets[i];
    if (id === curSocket.id) {
      return curSocket;
    }
  }
  return;
};

// 在客户端创建连接时调用
RTC.prototype.init = function(socket) {
  var rtc = this;
  socket.id = UUID.v4();
  rtc.addSocket(socket);

  //为新连接绑定事件处理器
  socket.on('__join', function(data) {
    console.log("join : socketId:" + socket.id);
    var ids = []; // 当前房间中所有的socketId（除了自己）
    var room = data || "__default"; // 房间名
    var curRoom = rtc.rooms[room] = rtc.rooms[room] || []; // 房间中所有的socketId

    for (var i = 0; i < curRoom.length; i++) {
      var curSocket = curRoom[i];
      if (curSocket.id === socket.id) {
        continue;
      }
      ids.push(curSocket.id);
      curSocket.emit("_new_peer", socket.id);
    }

    curRoom.push(socket);
    socket.room = room;
    socket.emit("_peers", ids, socket.id);
  });

  socket.on('__ice_candidate', function(sdpMid, label, candidate, socketId) {
    var targetSocket = rtc.getSocket(socketId);
    if (targetSocket) {
      var data = {
        "sdpMid": sdpMid,
        "label": label,
        "candidate": candidate,
        "socketId": socket.id
      };
      // targetSocket.send(data, errorCb);
      targetSocket.emit("_ice_candidate", data);
      // console.log('send iceCandidate : label:' + label + ' candidate:' + candidate + ' socketId:' + socketId);
    }
  });

  socket.on('__offer', function(sdp, socketId) {
    var targetSocket = rtc.getSocket(socketId);

    if (targetSocket) {
      targetSocket.emit("_offer", sdp, socket.id);
      console.log('send offer');
      console.log('  from:' + socket.id);
      console.log('  to:' + targetSocket.id);
    }
  });

  socket.on('__answer', function(sdp, socketId) {
    var targetSocket = rtc.getSocket(socketId);
    if (targetSocket) {
      targetSocket.emit("_answer", sdp, socket.id);
      console.log('send answer');
      console.log('  from:' + socket.id);
      console.log('  to:' + targetSocket.id);
    }
  });

  //连接关闭后从SkyRTC实例中移除连接，并通知其他连接
  socket.on('disconnect', function() {
    console.log("leave : socketId:" + socket.id);
    var i, m,
      room = socket.room,
      curRoom;
    if (room) {
      curRoom = rtc.rooms[room];
      for (i = curRoom.length; i--;) {
        if (curRoom[i].id === socket.id) {
          continue;
        }
        curRoom[i].emit("_remove_peer", socket.id);
      }
    }

    rtc.removeSocket(socket);
  });
};

module.exports = new RTC();
